package com.wan.net.session;

import com.wan.AppContext;
import com.wan.net.event.ChannelInactiveEvent;
import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class ChannelManager {
    private static final AtomicLong atomicLong = new AtomicLong(0);
    private final Map<Long, Channel> channelMap = new ConcurrentHashMap<>();

    public void add(Channel channel){
        initChannel(channel);
        channelMap.put(AttributeKeys.get(channel,AttributeKeys.CHANNEL_ID),channel);
    }

    private void initChannel(Channel channel){
        long channelId = atomicLong.incrementAndGet();
        AttributeKeys.set(channel,AttributeKeys.CHANNEL_ID,channelId);
    }

    public void remove(Channel channel){
        if(channelMap.remove(AttributeKeys.get(channel,AttributeKeys.CHANNEL_ID)) != null){
            AppContext.publishEvent(new ChannelInactiveEvent(channel));
        }
    }

    public Channel get(long channelId){
        return channelMap.get(channelId);
    }

}
